package com.jpyl.jpMedicalTreatment.view.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import android.widget.TextView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.google.gson.JsonObject;
import com.jpyl.jpMedicalTreatment.R;

import com.jpyl.jpMedicalTreatment.common.MedicalSettings;
import com.jpyl.jpMedicalTreatment.model.AgentMessageModel;
import com.jpyl.jpMedicalTreatment.model.DateOfCheckModel;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.PopwindowModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.model.RxSpf_UserModel;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;
import com.jpyl.jpMedicalTreatment.view.activity.BaseActivity;

import com.jpyl.jpMedicalTreatment.view.adapter.PatientAdapter;
import com.jpyl.jpMedicalTreatment.view.widget.sortlistview.MyPopupwindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * 患者列表
 * Created by 15697 on 2019/3/7.
 */

public class PatientListActivity extends BaseActivity {
    @BindView(R.id.rv_refresh_layout)
    RecyclerView rvRefreshLayout;
    @BindView(R.id.mr_refresh_layout)
    MaterialRefreshLayout mrRefreshLayout;
    @BindView(R.id.tv_refreshLayout_Empty)
    TextView tvRefreshLayoutEmpty;
    final RequestApi publicApi = Network.getRequestApi();
    List<AgentMessageModel> lists = new ArrayList<>();
    PatientAdapter adapter;

    MyPopupwindow popSituation, popCheckSituation; //出货情况/检查情况；（三种检查结果）
    List<PopwindowModel> list_popSituation = new ArrayList<>();  //出货情况，检查情况
    List<PopwindowModel> list_popCheckSituation = new ArrayList<>();//（三种检查结果）
    RxSpf_UserModel spfUserModel;
    List<DateOfCheckModel.RowsBean> list = new ArrayList<>();
    boolean isAgency;
    String userId = "", flag = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_refrsh_layout;
    }

    @Override
    public void afterCreate(Bundle savedInstanceState) {
        mTitleTv.setText("患者列表");
        list_popSituation = MedicalSettings.getSituation();
        list_popCheckSituation = MedicalSettings.getCheckSituation();
        spfUserModel = RxSpf_UserModel.create(this);
        isAgency = getIntent().getBooleanExtra("isDoctor", false);
        flag = getIntent().getStringExtra("flag");
        if (isAgency) {
            //代理商身份
            userId = getIntent().getStringExtra("userId");
        } else {
            //医生身份
            userId = spfUserModel.userId().get();
        }
        adapter = new PatientAdapter(getApplicationContext(), lists);
        rvRefreshLayout.setAdapter(adapter);
        rvRefreshLayout.setLayoutManager(new GridLayoutManager(this, 1));
        mrRefreshLayout.setLoadMore(false);
        mrRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                jpylQueryDoctorsByName(userId);
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                super.onRefreshLoadMore(materialRefreshLayout);
                materialRefreshLayout.finishRefreshLoadMore();

            }
        });


        adapter.setItemClickListener(new PatientAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position) {
                popSituation = new MyPopupwindow(PatientListActivity.this, list_popSituation);
                popSituation.show();
                popSituation.setCallBack(new MyPopupwindow.MyPopwindowListener() {
                    @Override
                    public void selectPositon(int i) {
                        if (list_popSituation.get(i).value == MedicalSettings.SITUATION_1) {
                            //出货情况
                            popSituation.dismiss();
                            startActivity(new Intent(getApplicationContext(),
                                    OutSituationActivity.class).putExtra("list", lists.get(i))
                                    .putExtra("flag", flag));
                        } else {
                            popSituation.dismiss();
                            popCheckSituation = new MyPopupwindow(PatientListActivity.this,
                                    list_popCheckSituation);
                            popCheckSituation.show();
                            popCheckSituation.setCallBack(new MyPopupwindow.MyPopwindowListener() {
                                @Override
                                public void selectPositon(int i) {
                                    switch (list_popCheckSituation.get(i).value) {
                                        case MedicalSettings.SITUATION_3:
                                            popCheckSituation.dismiss();
                                            jpylGetHPV(lists.get(position).getId());

                                            break;
                                        case MedicalSettings.SITUATION_4:
                                            popCheckSituation.dismiss();
                                            jpylGetHP(lists.get(position).getId());

                                            break;
                                        case MedicalSettings.SITUATION_5:
                                            popCheckSituation.dismiss();
                                            jpylGetSe(lists.get(position).getId());
                                            break;
                                    }


                                }
                            });
                        }
                    }
                });
            }
        });

        jpylQueryDoctorsByName(userId);
    }


    private void jpylQueryDoctorsByName(String userid) {
        publicApi.jpylQueryMyPatientsByName(userid, "").map(new Func1<ResponseModel<List<AgentMessageModel>>, List<AgentMessageModel>>() {
            @Override
            public List<AgentMessageModel> call(ResponseModel<List<AgentMessageModel>>
                                                        responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<AgentMessageModel>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        } else {
                        }
                    }

                    @Override
                    public void onNext(List<AgentMessageModel> list) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        lists.clear();
                        lists.addAll(list);
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    /**
     * hpv列表
     */
    private void jpylGetHPV(String userid) {
        final JsonObject body = new JsonObject();
        body.addProperty("rows", "10");
        body.addProperty("page", 1 + "");
        int dateFrom = 0;
        int dateTo = 0;
        publicApi.jpylGetHPV(userid, body.toString(), dateFrom, dateTo).map(new Func1<ResponseModel<DateOfCheckModel>, DateOfCheckModel>() {
            @Override
            public DateOfCheckModel call(ResponseModel<DateOfCheckModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<DateOfCheckModel>() {
                    @Override
                    public void onCompleted() {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        } else {
                        }
                    }

                    @Override
                    public void onNext(DateOfCheckModel userModel) {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();
                        list.addAll(userModel.getRows());
                        startActivity(new Intent
                                (getApplicationContext(),
                                        CheckDetailsActivity
                                                .class)
                                .putExtra("title", "HPV").putExtra("list", list.get(0)).putExtra
                                        ("pos", 0));

                    }
                });
    }

    /**
     * hp列表
     */
    private void jpylGetHP(String userid) {
        final JsonObject body = new JsonObject();
        body.addProperty("rows", "10");
        body.addProperty("page", 1 + "");
        int dateFrom = 0;
        int dateTo = 0;

        publicApi.jpylGetHP(userid, body.toString(), dateFrom, dateTo).map(new Func1<ResponseModel<DateOfCheckModel>, DateOfCheckModel>() {
            @Override
            public DateOfCheckModel call(ResponseModel<DateOfCheckModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<DateOfCheckModel>() {
                    @Override
                    public void onCompleted() {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        } else {
                        }
                    }

                    @Override
                    public void onNext(DateOfCheckModel userModel) {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();
                        list.addAll(userModel.getRows());
                        startActivity(new Intent(getApplicationContext(),
                                CheckDetailsActivity.class)
                                .putExtra("title", "HP").putExtra("list", list.get(0)).putExtra
                                        ("pos", 1));
                    }
                });
    }

    /**
     * se列表
     */
    private void jpylGetSe(String userid) {
        final JsonObject body = new JsonObject();
        body.addProperty("rows", "10");
        body.addProperty("page", 1 + "");
        int dateFrom = 0;
        int dateTo = 0;

        publicApi.jpylGetSe(userid, body.toString(), dateFrom, dateTo).map(new Func1<ResponseModel<DateOfCheckModel>, DateOfCheckModel>() {
            @Override
            public DateOfCheckModel call(ResponseModel<DateOfCheckModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<DateOfCheckModel>() {
                    @Override
                    public void onCompleted() {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();

                    }

                    @Override
                    public void onError(Throwable e) {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();

                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        } else {
                        }
                    }

                    @Override
                    public void onNext(DateOfCheckModel userModel) {
                        mrRefreshLayout.finishRefreshLoadMore();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshing();

                        list.addAll(userModel.getRows());
                        startActivity(new Intent(getApplicationContext(),
                                CheckDetailsActivity.class)
                                .putExtra("title", "Se").putExtra("list", list.get(0)).putExtra
                                        ("pos", 2));
                    }
                });
    }
}
